package com.ltmonitor.web.controller.command;

import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 事件设置
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/terminalEvent")
public class TerminalEventAction extends TerminalCommandAction {
	
	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/command/terminalEventConfig";
	}


	/**
	 * 
	 * @param vehicleId
	 * @param eventList 
	 * @param configType 设置类型, 0：删除终端全部事件项； 1：更新事件； 2：追加事件； 3：修改事件 4:删除指定事件
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage execute(long vehicleId, String inserted, int configType) {

		// eventList = eventList.replaceAll("\\],\\[", ";").replaceAll("\"", "")
		// .replaceAll("\\[", "").replaceAll("\\]", "");
		try {
			Map params = super.getParams();

			JSONArray arry = JSONArray.fromObject(inserted);
			String eventList = "";
			StringBuilder errorMsg = new StringBuilder();
			int rowNo = 1;
			if (configType > 0) {
				for (int m = 0; m < arry.size(); m++) {
					JSONObject mi = arry.getJSONObject(m);
					if(mi.isNullObject())
					{
						return json(false,"请录入事件");
					}
					String ID = mi.getString("ID");
					String content = mi.getString("content");
					if (isNumeric(ID) == false)
						errorMsg.append("第一列").append(
								"第" + rowNo + "行必须为数字整数, ");
					if (configType != 4 && StringUtil.isNullOrEmpty(content))
						errorMsg.append("第二列").append("第" + rowNo + "行不能为空, ");
					eventList += ID + "," + content + ";";

					rowNo++;
				}
			}

			if (errorMsg.length() > 0)
				return json(false, errorMsg.toString());

			TerminalCommand tc = new TerminalCommand();
			tc.setVehicleId(vehicleId);
			tc.setCmdType(JT808Constants.CMD_EVENT_SET);
			tc.setCmdData(eventList);
			tc.setCmd("" + configType);
			SendCommand(tc);
			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	public static boolean isNumeric(String str) {
		if (str.matches("\\d*")) {
			return true;
		}
		return false;
	}


}
